package com.xiaoyu.lanling.feature.chat.model.message

import `in`.srain.cube.request.JsonData
import android.text.TextUtils
import com.xiaoyu.base.image.ImageLoadInfo
import com.xiaoyu.base.utils.FileUtil
import com.xiaoyu.im.datamodel.AppMessage
import com.xiaoyu.lanling.common.Constant.MessageAttrsKey.FIRST_PICTURE
import com.xiaoyu.lanling.common.Constant.MessageAttrsKey.LOCAL_FIRST_PICTURE
import com.xiaoyu.lanling.feature.chat.model.message.ChatImageSizer.getImageHeight
import com.xiaoyu.lanling.feature.chat.model.message.ChatImageSizer.getImageWidth
import com.xiaoyu.lanling.feature.chat.viewholder.ChatViewHolderManager

class ChatMessageReceiveVideoItem(message: AppMessage) : ChatMessageReceiveBaseItem(message) {
    val duration: Int
    val width: Int
    val height: Int
    var firstPicture: String? = getFirstPicture(message.payload.attrsCopy)
    val videoUrl: String
    override val childrenViewType: Int
        get() = ChatViewHolderManager.TYPE_RECEIVE_VIDEO

    init {
        duration = message.payload.duration
        firstPicture = message.payload.attrsCopy.optString(FIRST_PICTURE)
        videoUrl = message.payload.localPathOrUrlForMedia
        val imageLoadInfo = ImageLoadInfo(firstPicture)
        width = getImageWidth(imageLoadInfo)
        height = getImageHeight(imageLoadInfo)
    }

    private fun getFirstPicture(attrs: JsonData): String? {
        val localFirstPicture: String = attrs.optString(LOCAL_FIRST_PICTURE)
        if (!TextUtils.isEmpty(localFirstPicture) && FileUtil.isFileExist(localFirstPicture)) {
            return localFirstPicture
        }
        val firstPicture: String = attrs.optString(FIRST_PICTURE)
        return if (!TextUtils.isEmpty(firstPicture)) {
            firstPicture
        } else null
    }
}